local only_show_me = GetModConfigData("sw_nickname") == "only"
local only_color_white = false
local name_seed = 2022
local DATA_SEED = "NAMECOLOR_SEED"
local DATA_COL = "NAMECOLOR_COL"

local table_vip = {76561198322050251, 76561198426806125}

AddPrefabPostInit("world", function()
    name_seed = GLOBAL.tonumber(LoadModData(DATA_SEED)) or 2023
	only_color_white = LoadModData(DATA_COL) or false
end)

local function getColor(usrid)
	local color = {1, 1, 1, 1}
	if only_color_white ~= "white" then
		local data = GLOBAL.TheNet:GetClientTableForUser(usrid)
		local id = data and GLOBAL.tonumber(data.netid)
		if type(id) == "number" then
			if table.contains(table_vip, id) or only_color_white == "RGB" then
				math.randomseed(id%GLOBAL.os.time())
			else
				math.randomseed(id%name_seed)
			end
		else
			math.randomseed(name_seed)
		end
		return GLOBAL.GetRandomItem(GLOBAL.PLAYERCOLOURS)
	end
	return color
end
AddPlayerPostInit(function(player)
	player:DoTaskInTime(0.5, function(player)
		local me = player == GLOBAL.ThePlayer
		local label = player.entity:AddLabel()
		label:SetFontSize(19)         
		label:SetFont(GLOBAL.BODYTEXTFONT)
		label:SetWorldOffset(0, 2.3, 0)
		local name = player.name
		label:SetText(name)
		local color = getColor(player.userid)
		label:SetColour(GLOBAL.unpack(color))
		label:Enable(true)


		if player:IsValid() then
			player:DoPeriodicTask(0.5, function(player)				-- 哈哈哈哈哈哈，看我的炫彩
				local new_name = player.name
				if me and only_show_me then
					new_name = ""
				end
				if name ~= new_name and type(new_name) == "string" then
					name = new_name
					label:SetText(name or "")
				end
				local new_color = getColor(player.userid)
				if new_color ~= color then
					color = new_color
					label:SetColour(GLOBAL.unpack(color))
				end
			end)		
		end
	end)
end)

local function fn()
	if only_color_white == "white" then
		only_color_white = false
		name_seed = GLOBAL.os.time()
		SaveModData(DATA_SEED, name_seed)
		TIP("彩色昵称", "pink", "随机颜色", "chat")
	elseif only_color_white == false then
		only_color_white = "RGB"
		TIP("彩色昵称", "blue", "炫彩RGB", "chat")
	elseif only_color_white == "RGB" then
		only_color_white = "white"
		TIP("彩色昵称", "white", "仅白色", "chat")
	end
	SaveModData(DATA_COL, only_color_white)
end

DEAR_BTNS:AddDearBtn(GLOBAL.GetInventoryItemAtlas("beemine_heart.tex"), "beemine_heart.tex", "彩色昵称", "随机设置玩家昵称颜色", false,fn)